/**
 * This Class is used for any kind of situation and it instantiates a pop menu with the 
 * given abstractActions
 * @author zulianp@lu.unisi.ch
 */

package ch.unisi.inf.projects.java.uom.gui.itemeditor.fieldselector;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
//import java.awt.event.MouseListener;

import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public final class PopupActionJLabel extends JLabel{


	private static final long serialVersionUID = -1L;
	private final ArrayList<AbstractAction> actions;
	
	public PopupActionJLabel()
	{
		
		this.setToolTipText("Click to modify the entry");
		this.actions = new ArrayList<AbstractAction>();
		final MouseAdapter adapter =  new MouseAdapter() {
			public void mousePressed(final MouseEvent ev) {checkPopup(ev);}
			public void mouseReleased(final MouseEvent ev){checkPopup(ev);}
			public void mouseEntered(final MouseEvent ev) {
				setForeground(new Color(90,90,190));
			}
			public void mouseExited(final MouseEvent ev) {
				setForeground(Color.BLACK);
			}
			public void mouseClicked(final MouseEvent ev) {
				showPopup(ev);}};
			
		this.addMouseListener(adapter);
	}
	

	

	public void checkPopup(final MouseEvent ev)
	{
		if(ev.isPopupTrigger())
		{
			showPopup(ev);
		}
		
	}
	
	
	public void addAbstractAction(final AbstractAction a)
	{
		actions.add(a);
	}
	
	
	public void removeAbstractAction(final AbstractAction a)
	{
		actions.remove(a);
	}
	
	public void showPopup(final MouseEvent ev)
	{
		final JPopupMenu popupMenu = new JPopupMenu();
		for(final AbstractAction a : actions)
		{
			final JMenuItem menuItem = new JMenuItem(a);
			popupMenu.add(menuItem);
		}
		
		popupMenu.show(this,(int)ev.getX(),(int)ev.getY());
		
		
		
	}
}
